const util = require("../util/util.js");
const mysqldb = require("../util/db.js")

exports.service = async function (params, cb) {
    var db = new mysqldb.db()
    let cmd = params.cmd;
    var sql = await getcmd(cmd);
    if (sql) {
        var do_sql = util.replaceSqlField(sql, params.param);
        console.log(do_sql)
        var sql_arr = new Array();
        var sql_arr_1 = new Array();
        var redata = new Array();
        do_sql.indexOf(';') < 0 ? sql_arr.push(do_sql) : sql_arr = do_sql.split(';')
        sql_arr.forEach((sql) => {
            if (sql) {
                sql_arr_1.push(sql)
            }
        });
        var restatus = true;
        for (let i in sql_arr_1) {
            var data = await getdata(sql_arr_1[i])
            restatus = data.status ? restatus : false
            redata.push(data.data)
        }
        cb && cb(restatus, redata)
    }
    else {
        console.log("未找到接口SQL")
        cb && cb(false, "cmd wrong!")
    }
};

function getcmd(cmd) {
    return new Promise((resolve, rejectt) => {
        let sql = "select * from base_cmd where cmd='" + cmd + "'"
        var db = new mysqldb.db()
        db.getAll(sql, (err, data) => {
            if (err) {
                console.log(err)
                resolve('')
            }
            else if (data && data[0] && data[0].SQL) {
                resolve(data[0].SQL)
            } else {
                console.log(cmd + ":can not find")
                resolve('')
            }
        })
    })
};


function getdata(sql, params) {
    var db = new mysqldb.db()
    return new Promise((resolve, reject) => {
        db.getAll(sql, function (err, data) {
            if (err) {
                console.log(err)
                resolve({ status: false, data: err })
            }
            else if (data) {
                resolve({ status: true, data: data })
            }
        })
    })
}